package com.jf3q.restfuldemo.controller;

import com.jf3q.restfuldemo.vo.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author:xiaojie
 * @create: 2024-01-02 14:50
 * @Description:
 */
@RestController
public class UploadController {

    @Value("${web.upload-path}")
    String uploadPath;


    @PostMapping("/upload")
    public ResultVo upload(MultipartFile file){
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String format = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (file.getSize()>500*1024) {
                return ResultVo.error("文件超过了500k");
            }else if(
                    format.equalsIgnoreCase(".jpg")||
                    format.equalsIgnoreCase(".png")||
                    format.equalsIgnoreCase(".jpeg")||
                    format.equalsIgnoreCase(".gif")
            ){

                //正常上传
                String fileName= UUID.randomUUID().toString().replace("-","");
                File saveFile=new File(uploadPath+fileName+format);
                try {
                    file.transferTo(saveFile);
                    return ResultVo.success("文件上传成功",fileName+format);
                } catch (IOException e) {
                    return ResultVo.error("文件上传出现异常");
                }


            }else{
                return ResultVo.error("文件格式不对");
            }
        }else{
            return ResultVo.error("文件没选");
        }

    }
}
